import router from './router'
import store from './store'
import NProgress from 'nprogress' // Progress 进度条
import 'nprogress/nprogress.css' // Progress 进度条样式
import { Message } from 'element-ui'
import { getToken, getUserName, removeToken } from '@/utils/auth' // 验权

const whiteList = ['/login'] // 不重定向白名单
router.beforeEach((to, from, next) => {
  NProgress.start()
  if (getToken() && sessionStorage.token) {
    // 有token 曾经登录
    if (to.path === '/login') {
      next({ path: '/' })
    } else if (to.path === '/changepwd') {
      next()
    } else {
      // 默认代理系统
      // let infoDispatch = 'GetUserInfo'
      let userInfoLength = Object.keys(store.getters.info).length
      if (process.env.BASE_API === '/memberapi') {
        // 会员系统
        // infoDispatch = 'MemberGetInfo'
        userInfoLength = Object.keys(store.getters.memberInfo).length
      }
      // console.log('userInfoLength是什么', userInfoLength)
      // 注意对info为空的判断
      if (userInfoLength === 0) {
        const info = {
          username: getUserName(),
          level: 0,
        }
        store.commit('SET_INFO', info)
        next()
        // 拉取用户信息,成功后保存store
        // store
        //   .dispatch(infoDispatch, { username: getUserName(), set: true })
        //   .then(res => {
        //     next()
        //   })
        //   .catch(() => {
        //     store.dispatch('FedLogOut').then(() => {
        //       Message.error('验证失败,请重新登录')
        //       next({ path: '/login' })
        //     })
        //   })
      } else {
        next()
      }
    }
  } else {
    // removeToken() // 删除cookie信息
    if (whiteList.indexOf(to.path) !== -1) {
      next()
    } else {
      next('/login')
      NProgress.done()
    }
  }
})

router.afterEach(() => {
  NProgress.done() // 结束Progress
})
